/*
给定可能含有重复值数组arr找到每一个i位置左边和右边离i位置最近且值比arr[i]小的位置。返回所有位置相应的信息。
arr = [3,1,3,4,3,5,3,2,2]
res: [[-1,1],[-1,-1],[1,7],[2,4],[1,7],[4,6],[1,7],[1,-1],[1,-1]]
 */

Array.prototype.getLast = function () {
  return this[this.length - 1]
}

Array.prototype.getFirst = function () {
  return this[0]
}

/**
 *
 * @param {number[]} arr
 * @return {number[][]}
 */
function getNearLessNumPositionRepeat (arr) {
  const res = new Array(arr.length)
  const monoStack = []
  for (let i = 0, n = arr.length; i < n; i++) {
    while (monoStack.length && arr[monoStack.getLast().getFirst()] > arr[i]) {
      const equalIndexes = monoStack.pop()
      equalIndexes.forEach(value => {
        const tempRes = []
        tempRes[0] = monoStack.length ? monoStack.getLast().getLast() : -1
        tempRes[1] = i
        res[value] = tempRes
      })
    }
    if (monoStack.length && arr[monoStack.getLast().getFirst()] === arr[i]) {
      monoStack.getLast().push(i)
    } else {
      monoStack.push([i])
    }
  }
  while (monoStack.length) {
    const equalIndexes = monoStack.pop()
    equalIndexes.forEach(value => {
      const tempRes = []
      tempRes[0] = monoStack.length ? monoStack.getLast().getLast() : -1
      tempRes[1] = -1
      res[value] = tempRes
    })
  }
  return res
}

console.log(getNearLessNumPositionRepeat([3, 1, 3, 4, 3, 5, 3, 2, 2]))
